package com.ideal.hadoopadmin.web.controller.system.role;

import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.common.util.MenuTree;
import com.ideal.hadoopadmin.common.util.MenuTreeCheck;
import com.ideal.hadoopadmin.entity.main.Menu;
import com.ideal.hadoopadmin.entity.main.RoleMenu;
import com.ideal.hadoopadmin.entity.system.Role;
import com.ideal.hadoopadmin.framework.message.WebMessageLevel;
import com.ideal.hadoopadmin.framework.web.json.JsonObject;
import com.ideal.hadoopadmin.service.main.RoleMenuService;
import com.ideal.hadoopadmin.service.main.SystemMenuService;
import com.ideal.hadoopadmin.service.system.RoleService;
import com.ideal.hadoopadmin.web.controller.UIController;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by fwj on 16-3-8.
 * 角色管理
 */
@Controller
@RequestMapping(RoleManageController.PORTAL_PREFIX)
public class RoleManageController extends UIController {
    Logger logger = LoggerFactory.getLogger(RoleManageController.class);
    public final static String PORTAL_PREFIX = "/system/role";

    @Resource
    public RoleService roleService;
    @Resource
    public SystemMenuService systemMenuService;
    @Resource
    public RoleMenuService roleMenuService;

    @RequestMapping("role_manage")
    public void index(HttpServletRequest request, Model model) throws Exception {
        Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, "Q_");
        PageInfo page = roleService.queryRoleList(searchParams, request);
        model.addAttribute("page", page);
    }

    @RequestMapping("edit_role_pop")
    public void edit(Model model, @RequestParam(value = "id", required = false) Long id) {
        Role roleInfo = null;
        if (id != null) {
            roleInfo = roleService.queryRoleById(id);
        }
        model.addAttribute("roleInfo", roleInfo);
    }

    //
    @RequestMapping("save_role")
    @ResponseBody
    public JsonObject save(Model model, @RequestParam(value = "id") Long id,
                           @RequestParam(required = false) String cn_name) {
        try {
            Role role = new Role();
            if (id != null) {
                Role queryRoleById = roleService.queryRoleById(id);
                role.setId(id);
                role.setName(cn_name);
                role.setStatus(queryRoleById.getStatus());
                role.setCreateTime(new Date().getTime());
                roleService.updateRole(role);
                return JsonObject.alert("修改角色成功",WebMessageLevel.SUCCESS);
            } else {
                role.setName(cn_name);
                role.setStatus("0");
                role.setCreateTime(new Date().getTime());
                roleService.saveRole(role);
                return JsonObject.alert("添加角色成功",WebMessageLevel.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return JsonObject.error("添加角色失败");

    }

    @RequestMapping("delete_role")
    @ResponseBody
    public JsonObject delete(@RequestParam(value = "id") Long[] ids) {
        //判断需要删除的7
        if (ids != null) {
            String errorMessage = roleService.deleteeRoleByID(ids);
            //如果有正在使用的角色，提示无法删除
            if (errorMessage != null && errorMessage.length() > 0) {
                errorMessage = errorMessage + "角色正在使用中，无法删除！，请到账户管理处删除或修改该角色";
                return JsonObject.alert(errorMessage, WebMessageLevel.ERROR);
            }
        }
        return JsonObject.alert("删除成功", WebMessageLevel.SUCCESS);
    }

    //
    @RequestMapping("authority_role_pop")
    public void authority(Model model, @RequestParam(value = "id", required = false) Long id) throws Exception {
        List<Menu> allMenus = systemMenuService.queryMenuAllList();
        List<MenuTreeCheck> menuTreeList = new ArrayList<MenuTreeCheck>();
        for (Menu m : allMenus) {
            RoleMenu roleMenu = roleMenuService.queryRoleMenuByRoleIdAndMenuId(id, m.getId());
            if (null != roleMenu) {
                menuTreeList.add(new MenuTreeCheck(m.getId(), m.getParentId() == null ? null : m.getParentId(), m.getTitle(), false, true));
            } else {
                menuTreeList.add(new MenuTreeCheck(m.getId(), m.getParentId() == null ? null : m.getParentId(), m.getTitle(), false, false));
            }
        }
        String menuTreeStr = JSONArray.fromObject(menuTreeList).toString();
        model.addAttribute("menuTree", menuTreeStr);
        model.addAttribute("roleId", id);
    }

    //
    @RequestMapping("save_roleMenu")
    @ResponseBody
    public JsonObject saveRoleMenu(String menuIds, Long roleId) {
        try {
            List<RoleMenu> roleMenus = roleMenuService.queryRoleMenuByRoleId(roleId);
            if (roleMenus != null) {
                roleMenuService.deleteRoleMenuByRoleIdAndMeuId(roleMenus);
            }
            String[] str = menuIds.split(",");
            for (String s : str) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                Long menuId = Long.parseLong(s);
                roleMenu.setMenuId(menuId);
                roleMenuService.saveRoleMenu(roleMenu);
            }
            return JsonObject.success("授权成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return JsonObject.alert("授权失败", WebMessageLevel.SUCCESS);
    }


    @Override
    public String getPortalPrefix() {
        return PORTAL_PREFIX;
    }
}
